<!--出库单-->
<template>
  <div class="outbound-order-container">
    <!-- 筛选区域 -->
    <div class="controls-section">
        <button class="btn-new" @click="onAdd">新建</button>
        <div class="filters">
            <div class="filter-item">
                <label>关键词</label>
                <input type="text" placeholder="请输入出库单号" v-model="query.keyword">
            </div>
            <div class="filter-item">
                <label>出库状态</label>
                <select v-model="query.outboundStatus">
                    <option value="">全部</option>
                    <option value="0">待出库</option>
                    <option value="1">部分出库</option>
                    <option value="2">全部出库</option>
                </select>
            </div>
        </div>
        <div class="actions">
            <button class="btn-primary" @click="onSearch">搜索</button>
            <button class="btn-secondary" @click="onReset">重置</button>
        </div>
    </div>

    <!-- 表格区域 -->
    <div class="table-section">
      <table>
        <thead>
          <tr>
            <th><input type="checkbox" v-model="allSelected"></th>
            <th>出库单号</th>
            <th>出库状态</th>
            <th>出库时间</th>
            <th>出库类型</th>
            <th>出库数量</th>
            <th>出库产品数</th>
            <th>出库人</th>
            <th>关联销售单</th>
            <th>生产工单</th>
            <th>采购单</th>
            <th>备注</th>
          </tr>
        </thead>
        <tbody>
          <tr v-if="loading">
            <td colspan="12" style="text-align: center; padding: 20px;">加载中...</td>
          </tr>
          <tr v-else-if="orders.length === 0">
            <td colspan="12" style="text-align: center; padding: 20px;">暂无数据</td>
          </tr>
          <tr v-else v-for="(item, index) in orders" :key="index">
            <td><input type="checkbox" v-model="item.selected"></td>
            <td class="link-style" @click="viewDetail(item)">{{ item.outboundNo || '-' }}</td>
            <td><span :class="getStatusClass(item.outboundStatus)">{{ getStatusText(item.outboundStatus) }}</span></td>
            <td>{{ formatDate(item.outboundTime) }}</td>
            <td>{{ getTypeText(item.outboundType) }}</td>
            <td>{{ item.outboundQuantity || '-' }}</td>
            <td>{{ item.productCount || '-' }}</td>
            <td>{{ item.username || item.uId || '-' }}</td>
            <td>{{ item.orderNo || '-' }}</td>
            <td>{{ item.workOrderNo || '-' }}</td>
            <td>{{ item.purchaseOrderNo || '-' }}</td>
            <td>{{ item.remark || '-' }}</td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 底部区域 -->
    <div class="footer-section">
      <div class="footer-left">
        <input type="checkbox" v-model="allSelected">
        <label>全选</label>
        <button class="btn-secondary" @click="onExport">导出</button>
      </div>
      <div class="pagination-info">
        共 {{ total }} 条记录，第 {{ query.current }} / {{ totalPages || 1 }} 页
      </div>
      <div class="pagination">
        <button @click="onPageChange(query.current - 1)" :disabled="query.current === 1">&lt;</button>
        <button v-for="page in visiblePages" :key="page" @click="onPageChange(page)" :class="{ active: query.current === page }">{{ page }}</button>
        <button @click="onPageChange(query.current + 1)" :disabled="query.current === totalPages">&gt;</button>
        <select v-model.number="query.size" @change="onPageSizeChange">
          <option value="10">10条/页</option>
          <option value="20">20条/页</option>
          <option value="50">50条/页</option>
        </select>
      </div>
    </div>

    <!-- 新增弹窗 -->
    <el-dialog v-model="addVisible" title="新建出库单" width="600px">
      <div class="form-grid">
        <div class="form-item">
          <div class="label">出库单号</div>
          <div class="field"><el-input v-model="addForm.outboundNo" placeholder="系统自动生成" disabled /></div>
        </div>
        <div class="form-item">
          <div class="label">出库类型</div>
          <div class="field">
            <el-select v-model="addForm.outboundType" placeholder="请选择">
              <el-option label="销售出库" :value="0" />
              <el-option label="生产领料" :value="1" />
              <el-option label="委外发料" :value="2" />
              <el-option label="采购退货" :value="3" />
              <el-option label="其他出库" :value="4" />
            </el-select>
          </div>
        </div>
        <div class="form-item">
          <div class="label">出库数量</div>
          <div class="field"><el-input-number v-model="addForm.outboundQuantity" :min="1" /></div>
        </div>
        <div class="form-item">
          <div class="label">产品数量</div>
          <div class="field"><el-input-number v-model="addForm.productCount" :min="1" /></div>
        </div>
        <div class="form-item">
          <div class="label">备注</div>
          <div class="field"><el-input v-model="addForm.remark" type="textarea" /></div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitAdd">提 交</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 详情弹窗 -->
    <el-dialog v-model="detailVisible" title="出库单详情" width="720px">
      <div class="detail-grid">
        <div class="detail-item">
          <div class="label">出库单号</div>
          <div class="value">{{ detailData.outboundNo || '-' }}</div>
        </div>
        <div class="detail-item">
          <div class="label">出库状态</div>
          <div class="value"><span :class="getStatusClass(detailData.outboundStatus)">{{ getStatusText(detailData.outboundStatus) }}</span></div>
        </div>
        <div class="detail-item">
          <div class="label">出库时间</div>
          <div class="value">{{ formatDate(detailData.outboundTime) }}</div>
        </div>
        <div class="detail-item">
          <div class="label">出库类型</div>
          <div class="value">{{ getTypeText(detailData.outboundType) }}</div>
        </div>
        <div class="detail-item">
          <div class="label">出库数量</div>
          <div class="value">{{ detailData.outboundQuantity || '-' }}</div>
        </div>
        <div class="detail-item">
          <div class="label">产品数量</div>
          <div class="value">{{ detailData.productCount || '-' }}</div>
        </div>
        <div class="detail-item">
          <div class="label">出库人</div>
          <div class="value">{{ detailData.username || detailData.uId || '-' }}</div>
        </div>
        <div class="detail-item">
          <div class="label">关联销售单</div>
          <div class="value">{{ detailData.orderNo || '-' }}</div>
        </div>
        <div class="detail-item">
          <div class="label">生产工单</div>
          <div class="value">{{ detailData.workOrderNo || '-' }}</div>
        </div>
        <div class="detail-item">
          <div class="label">采购单</div>
          <div class="value">{{ detailData.purchaseOrderNo || '-' }}</div>
        </div>
        <div class="detail-item">
          <div class="label">备注</div>
          <div class="value">{{ detailData.remark || '-' }}</div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailVisible = false">关 闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { fuzzySearchOutbound, addOutboundOrder, getOutboundDetail } from '@/api/warehouse/OutboundOrder'
import { ElMessage } from 'element-plus'

export default {
  name: 'OutboundOrder',
  data() {
    return {
      loading: false,
      // 查询条件
      query: {
        keyword: '',
        outboundStatus: '',
        current: 1,
        size: 10
      },
      // 分页数据
      total: 0,
      orders: [],
      // 新增弹窗
      addVisible: false,
      addForm: {
        outboundNo: '',
        outboundType: '',
        outboundQuantity: 1,
        productCount: 1,
        remark: ''
      },
      // 详情弹窗
      detailVisible: false,
      detailData: {}
    };
  },
  computed: {
    allSelected: {
      get() {
        return this.orders.length > 0 && this.orders.every(item => item.selected);
      },
      set(value) {
        this.orders.forEach(item => {
          item.selected = value;
        });
      }
    },
    totalPages() {
      return Math.ceil(this.total / this.query.size);
    },
    visiblePages() {
      const pages = [];
      const totalPages = this.totalPages;
      const current = this.query.current;

      if (totalPages <= 5) {
        for (let i = 1; i <= totalPages; i++) {
          pages.push(i);
        }
      } else {
        if (current <= 3) {
          pages.push(1, 2, 3, 4, totalPages);
        } else if (current >= totalPages - 2) {
          pages.push(1, totalPages - 3, totalPages - 2, totalPages - 1, totalPages);
        } else {
          pages.push(1, current - 1, current, current + 1, totalPages);
        }
      }
      return pages;
    }
  },
  mounted() {
    console.log('OutboundOrder组件已挂载，开始获取数据...')
    this.fetchList()
  },
  methods: {
    async fetchList() {
      try {
        this.loading = true
        const payload = {
          keyword: this.query.keyword || undefined,
          outboundStatus: this.query.outboundStatus === '' ? undefined : Number(this.query.outboundStatus),
          pageNum: this.query.current,
          pageSize: this.query.size
        }
        console.log('发送查询参数:', payload)
        const res = await fuzzySearchOutbound(payload)
        console.log('API响应:', res)

        if (res.code === 200 && res.data) {
          const data = res.data
          console.log('解析后的数据:', data)
          this.orders = (data.records || []).map(r => ({ ...r, selected: false }))
          this.total = data.total || 0
          console.log('设置到组件的orders:', this.orders)
          console.log('设置到组件的total:', this.total)
        } else {
          console.warn('API返回异常:', res)
          this.orders = []
          this.total = 0
          if (res.message) {
            ElMessage.warning(res.message)
          }
        }
      } catch (error) {
        console.error('获取出库单列表失败:', error)
        ElMessage.error('获取出库单列表失败: ' + (error.message || '未知错误'))
        this.orders = []
        this.total = 0
      } finally {
        this.loading = false
      }
    },

    onSearch() {
      this.query.current = 1
      this.fetchList()
    },

    onReset() {
      this.query = { keyword: '', outboundStatus: '', current: 1, size: 10 }
      console.log('重置查询条件:', this.query)
      this.fetchList()
    },

    onPageChange(page) {
      const totalPages = Math.max(1, Math.ceil(this.total / this.query.size))
      const next = Math.min(Math.max(1, page), totalPages)
      if (next === this.query.current) return
      this.query.current = next
      this.fetchList()
    },

    onPageSizeChange() {
      this.query.current = 1
      this.fetchList()
    },

    async onAdd() {
      this.resetAddForm()
      this.addVisible = true
    },

    async submitAdd() {
      const { outboundType, outboundQuantity, productCount, remark } = this.addForm
      if (outboundType === '' || !outboundQuantity || !productCount) {
        ElMessage.error('请填写必填项')
        return
      }
      try {
        await addOutboundOrder({ outboundType, outboundQuantity, productCount, remark })
        ElMessage.success('新增成功')
        this.addVisible = false
        this.fetchList()
      } catch (e) {
        // 错误统一由 http 拦截器提示
      }
    },

    resetAddForm() {
      this.addForm = {
        outboundNo: '',
        outboundType: '',
        outboundQuantity: 1,
        productCount: 1,
        remark: ''
      }
    },

    async viewDetail(row) {
      if (!row?.id) return
      try {
        const res = await getOutboundDetail(row.id)
        this.detailData = res.data?.data || {}
        this.detailVisible = true
      } catch (e) {
        ElMessage.error('获取详情失败')
      }
    },

    async onExport() {
      try {
        // 导出功能待实现
        ElMessage.success('导出成功')
      } catch (e) {
        ElMessage.error('导出失败')
      }
    },

    getStatusClass(status) {
      const statusMap = {
        0: 'status-pending',   // 待出库
        1: 'status-partial',   // 部分出库
        2: 'status-completed'  // 全部出库
      }
      return statusMap[status] || 'status-unknown'
    },

    getStatusText(status) {
      const statusMap = {
        0: '待出库',
        1: '部分出库',
        2: '全部出库'
      }
      return statusMap[status] || '未知状态'
    },

    getTypeText(type) {
      const typeMap = {
        0: '销售出库',
        1: '生产领料',
        2: '委外发料',
        3: '采购退货',
        4: '其他出库'
      }
      return typeMap[type] || '未知类型'
    },

    formatDate(dateStr) {
      if (!dateStr) return '-'
      try {
        const date = new Date(dateStr)
        if (isNaN(date.getTime())) return dateStr
        return date.toLocaleDateString('zh-CN')
      } catch (e) {
        return dateStr
      }
    }
  }
}
</script>

<style scoped>
.outbound-order-container {
  padding: 20px;
  background: #f5f5f5;
  min-height: 100vh;
}

.controls-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 20px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.btn-new {
  background: #409eff;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background 0.3s;
}

.btn-new:hover {
  background: #337ecc;
}

.filters {
  display: flex;
  gap: 20px;
  flex: 1;
}

.filter-item {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.filter-item label {
  font-size: 12px;
  color: #606266;
  font-weight: 500;
}

.filter-item input,
.filter-item select {
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 14px;
  min-width: 200px;
}

.filter-item input:focus,
.filter-item select:focus {
  outline: none;
  border-color: #409eff;
}

.actions {
  display: flex;
  gap: 10px;
}

.btn-primary,
.btn-secondary {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
}

.btn-primary {
  background: #409eff;
  color: white;
}

.btn-primary:hover {
  background: #337ecc;
}

.btn-secondary {
  background: #909399;
  color: white;
}

.btn-secondary:hover {
  background: #73767a;
}

.table-section {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #ebeef5;
}

th {
  background: #fafafa;
  font-weight: 600;
  color: #606266;
  font-size: 14px;
}

td {
  color: #606266;
  font-size: 14px;
}

tbody tr:hover {
  background: #f5f7fa;
}

.link-style {
  color: #409eff;
  cursor: pointer;
  text-decoration: underline;
}

.link-style:hover {
  color: #337ecc;
}

.status-pending {
  color: #e6a23c;
  background: #fdf6ec;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.status-partial {
  color: #409eff;
  background: #ecf5ff;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.status-completed {
  color: #67c23a;
  background: #f0f9ff;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.status-unknown {
  color: #909399;
  background: #f4f4f5;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.footer-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-top: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.footer-left {
  display: flex;
  align-items: center;
  gap: 10px;
}

.pagination-info {
  color: #606266;
  font-size: 14px;
}

.pagination {
  display: flex;
  gap: 5px;
  align-items: center;
}

.pagination button {
  padding: 6px 12px;
  border: 1px solid #dcdfe6;
  background: white;
  color: #606266;
  cursor: pointer;
  border-radius: 4px;
  transition: all 0.3s;
}

.pagination button:hover:not(:disabled) {
  border-color: #409eff;
  color: #409eff;
}

.pagination button.active {
  background: #409eff;
  color: white;
  border-color: #409eff;
}

.pagination button:disabled {
  color: #c0c4cc;
  cursor: not-allowed;
}

.pagination select {
  padding: 6px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  margin-left: 10px;
}

.form-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
}

.form-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-item .label {
  font-weight: 500;
  color: #606266;
}

.form-item .field {
  flex: 1;
}

.detail-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
}

.detail-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.detail-item .label {
  font-weight: 500;
  color: #606266;
  font-size: 14px;
}

.detail-item .value {
  color: #606266;
  font-size: 14px;
  padding: 8px 12px;
  background: #f5f7fa;
  border-radius: 4px;
  min-height: 20px;
}

.dialog-footer {
  text-align: right;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .form-grid,
  .detail-grid {
    grid-template-columns: 1fr;
  }

  .filters {
    flex-direction: column;
    gap: 15px;
  }

  .controls-section {
    flex-direction: column;
    align-items: stretch;
  }
}

@media (max-width: 768px) {
  .outbound-order-container {
    padding: 10px;
  }

  .controls-section,
  .table-section,
  .footer-section {
    padding: 15px;
  }

  .filters {
    gap: 10px;
  }

  .filter-item input,
  .filter-item select {
    min-width: auto;
  }
}
</style>
